<script lang="ts" setup>
import { getEnvironmentalPerformance, getIsListedCompany, type IEnvironment } from '../../../../apis';
import IndicatorTable from '../../../../components/indicator-table.vue';
import PageHeader from '../../../../components/page-header.vue';
import { useF9Context } from '@/views/modules/enterprise/use/use-context';

interface Props {
  title: string;
  menuId: string;
  count?: number;
}

enum CompanyEnum {
  GROUP_COMPANY = 1,
  THE_COMPANY = 2
}

const { title, menuId } = defineProps<Props>();

const { companyId } = useF9Context();

const requestParams = reactive<IEnvironment>({
  companyId,
  isKeyIndicators: false,
  isBlankLine: false,
  companyType: 1
});

let companyType = $ref(1);

let noData = $ref(false);

onMounted(async () => {
  // 获取公司类型
  const data = await getIsListedCompany(companyId);
  if (data) {
    companyType = CompanyEnum.GROUP_COMPANY;
  } else {
    companyType = CompanyEnum.THE_COMPANY;
  }
  
});

const {
  data: originData,
  run: getData,
  loading,
  error
} = useRequest(getEnvironmentalPerformance, {
  defaultParams: [requestParams],
  onSuccess(data) {
    if (data?.details?.length === 0) {
      noData = true;
    } else if ((!data?.details || data?.details?.length === 0 )  && data?.hasParentCompanyData) {
      if (companyType === CompanyEnum.GROUP_COMPANY) {
        companyType = CompanyEnum.THE_COMPANY;
      } else {
        companyType = CompanyEnum.GROUP_COMPANY;
      }
    } else {
      noData = false;
    }
  }
});

watch(
  () => companyType,
  (nv) => {
    requestParams.companyType = nv;
    getData(requestParams);
  }
);

const tableChange = (val) => {
  requestParams.isKeyIndicators = val;
  getData(requestParams);
};
</script>
<template>
  <page-header class="mt-18px mb-15px" :title="title" :menuId="menuId" is-small />
  <vc-empty-fail @click="getData(requestParams)" v-if="error || noData" />
  <indicator-table
    v-else
    v-model:companyType="companyType"
    :loading="loading"
    :details-data="originData?.details"
    :years-data="originData?.years"
    :hasParentCompanyData="originData?.hasParentCompanyData"
    @change="tableChange"
  />
</template>
